<template>
  <div v-loading="loading">
    <div class="flex-between mb-10">
      <div></div>

      <el-space size="default">
        <el-button type="primary" icon="UploadFilled" @click="openUpload"
          >上传附件</el-button
        >
      </el-space>
    </div>
    <common-table
      :table-type="filetableType"
      :table-data="tableData"
      :on-selection-change="onSelectionChange"
      v-model:total="currentTotal"
      v-model:page="currentPage"
      :handle-current-change="handleCurrentChange"
      :showPagination="true"
    >
      <template #operation>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button link type="danger" @click="onDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </common-table>
    <FileFormDialog ref="FileFormDialogRef" @refresh="refresh" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "@/api";
import { filetableType } from "./utils";
import FileFormDialog from "./FileFormDialog.vue";

const FileFormDialogRef = ref();
const loading = ref(false);

const tableData = ref<any[]>([]);
const tableSelection = ref<any[]>([]);
const onSelectionChange = (val: any[]) => {
  tableSelection.value = val;
};
const userAcc = localStorage.getItem("userAcc") as string;

/*
 * Static state
 * */
function getTableData(val: number) {
  loading.value = true;
  api.file
    .listPageFile(val, 20, userAcc)
    .then((res: any) => {
      if (res.success) {
        tableData.value = res.data.records;
        currentTotal.value = res.data.total;
        loading.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
}

//Import

function openUpload() {
  FileFormDialogRef.value.open();
}

//Delete
function onDelete(row: any) {
  ElMessageBox.confirm(`确认删除 ${row.fileName} 吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.file.deleteFile(row.id).then((res: any) => {
      ElMessage({
        message: res.message,
        type: res.success ? "success" : "error",
        grouping: true,
        showClose: true,
      });
      refresh();
    });
  });
}

//Pager
const currentPage = ref(1);
const currentTotal = ref(0);
const handleCurrentChange = (val: number) => {
  getTableData(val);
};

function refresh() {
  getTableData(currentPage.value);
}

onMounted(() => {
  getTableData(1);
});
</script>
